import 'dart:io';

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:guochaoapp/common/constant/api.dart';
import 'package:guochaoapp/common/utils/http_client.dart';
import 'package:guochaoapp/config/container.dart';
import 'package:guochaoapp/controller/mall_controller.dart';
import 'package:guochaoapp/controller/tabbar_controller.dart';
import 'package:guochaoapp/model/banner_entity.dart';
import 'package:guochaoapp/model/benchmark_entity.dart';
import 'package:guochaoapp/model/productbrand_entity.dart';
import 'package:guochaoapp/model/telephone_entity.dart';
import 'package:guochaoapp/model/userdealers_entity.dart';
import 'package:guochaoapp/model/version_entity.dart';
import 'package:guochaoapp/routes/app_pages.dart';
import 'package:guochaoapp/services/user_service.dart';
import 'package:package_info/package_info.dart';
import 'package:url_launcher/url_launcher.dart';

class GCHomeController extends GetxController {
  UserService userService = Get.find();
  GCTabbarController tabbarController = Get.find();

  /*城市信息*/
  var cityName = "上海".obs;

  /*价格涨跌*/
  var productbrandList = RxList<ProductbrandData>.empty();
  var brandSelectIndex = 0;
  var maxBenchmark = 1.0;
  var minBenchmark = 0.0;

  /*图表数据*/
  var benchmarkList = RxList<BenchmarkData>.empty();
  List<BarChartGroupData> barchatGroupList = [];

  /*轮播图*/
  var bannerList = RxList<BannerData>.empty();

  /*电话号码*/
  var telephone = "";

  /*版本号*/
  var versionData = VersionData().obs;

  /*刷新当前页面数据*/
  reloadStateWithDealer(UserdealersData userdealersData) {
    cityName.value = userdealersData.location;
    requestTelephone();
    requestProductBrand();
  }

  /*
  * 网络请求
  * */

  requestVersion() {
    HttpClient.request<VersionEntity>(
        url: VersionApi.version,
        method: Method.GET,
        onSuccess: (_, model) async {
          versionData.value = model.data;

          PackageInfo packageInfo = await PackageInfo.fromPlatform();
          String version = packageInfo.version;

          if (versionData.value.presentVersion == version) {
            return;
          } else {
            if (versionData.value.lastAvailable) {
              return;
            } else {
              if (Platform.isIOS) {
                showCupertinoDialog(
                    context: Get.context,
                    barrierDismissible: false,
                    builder: (ctx) {
                      return CupertinoAlertDialog(
                        content: Text("有新版本,前往更新后使用",
                            style: TextStyle(
                                fontSize: 16, fontWeight: FontWeight.bold)),
                        actions: <Widget>[
                          CupertinoDialogAction(
                              child: Text("好", style: TextStyle(fontSize: 14)),
                              onPressed: () => toAppStore()),
                        ],
                      );
                    });
              } else if (Platform.isAndroid) {

              }
            }
          }
        });
  }

  /*轮播图*/
  requestBannerList() {
    HttpClient.request<BannerEntity>(
        url: BannerApi.banners,
        method: Method.GET,
        onSuccess: (_, model) async {
          bannerList.assignAll(model.data);
        });
  }

  /*联系电话*/
  requestTelephone() {
    HttpClient.request<TelephoneEntity>(
        url: TelephoneApi.telephone,
        params: {"dealerId": userService.dealerId},
        method: Method.GET,
        onSuccess: (_, model) async {
          telephone = model.data.telephone;
        });
  }

  /*查询成品管的品牌列表*/
  requestProductBrand() {
    HttpClient.request<ProductbrandEntity>(
        url: ProductBrandApi.productBrand,
        params: {"dealerId": userService.dealerId},
        method: Method.GET,
        onSuccess: (_, model) async {
          productbrandList.assignAll(model.data);

          requestBenchmark();
        });
  }

  /*查询基准价格变更*/
  requestBenchmark() {
    HttpClient.request<BenchmarkEntity>(
        url: BenchmarkApi.benchmark,
        params: {
          "dealerId": userService.dealerId,
          "brandId": productbrandList[brandSelectIndex].brandId,
          "interval": "0",
          "size": "6"
        },
        method: Method.GET,
        onSuccess: (_, model) async {
          List<BarChartGroupData> list = [];

          double maxValue = 0;
          double minValue = 0;

          for (int i = 0; i < model.data.length; i++) {
            if (i == 0) {
              maxValue = model.data[i].currentBenchmark;
              minValue = model.data[i].currentBenchmark;
            }

            if (model.data[i].currentBenchmark > maxValue) {
              maxValue = model.data[i].currentBenchmark;
            }

            if (model.data[i].currentBenchmark < minValue) {
              minValue = model.data[i].currentBenchmark;
            }
          }

          maxBenchmark = maxValue;
          minBenchmark = minValue;

          for (int i = 0; i < model.data.length; i++) {
            list.add(_makeGroupData(i, model.data[i].currentBenchmark));
          }

          barchatGroupList = list;
          benchmarkList.assignAll(model.data);
        });
  }

  BarChartGroupData _makeGroupData(int x, double y1) {
    return BarChartGroupData(barsSpace: 4, x: x, barRods: [
      BarChartRodData(
        y: y1,
        colors: [Color(0xFF238189)],
        width: 4,
      ),
    ]);
  }

  /*
  * 点击事件都在下面
  * */

  /*左上角 城市点击*/
  localtonTap() {
    Get.toNamed(Routes.SELECTREGION);
  }

  /*右上角 客服按钮*/
  kfTap() {
    if (userService.isLogin) {
      if (telephone == null) {
        requestTelephone();
      } else {
        launch("tel://" + telephone);
      }
    } else {
      userService.removeUserInfo();
      Get.toNamed(Routes.LOGIN);
    }
  }

  /*中左 商城*/
  toShopping() {
    tabbarController.updateIndex(2);
  }

  /*中右 定制*/
  toBarcket() {
    tabbarController.updateIndex(1);
  }

  /*跳转详情页面*/
  toBenchMarkDetail() {
    Get.toNamed(Routes.BENCHMARKDETAIL, arguments: [
      productbrandList,
      benchmarkList,
    ]);
  }

  toAppStore() async {
    final url =
        "https://itunes.apple.com/cn/app/id1445532465"; // id 后面的数字换成自己的应用 id 就行了
    if (await canLaunch(url)) {
      await launch(url, forceSafariVC: false);
    } else {
      throw 'Could not launch $url';
    }
  }

  toMalls(int index) {
    tabbarController.updateIndex(1);

    GCMallController mallController = Get.find();
    mallController.firstCategoryItemTap(index);
  }
}
